package com.test.fundible.fundible_05_process.widget;

import static com.test.fundible.fundible_00_utils.FundibleUtil.startLoading;
import static com.test.fundible.fundible_00_utils.FundibleUtil.stopLoading;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.PickVisualMediaRequest;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.core.content.FileProvider;
import androidx.fragment.app.FragmentActivity;

import com.test.fundible.R;
import com.test.fundible.fundible_01_launcher.Base_fundibleApplication;
import com.test.fundible.fundible_05_process.Proces_fundiblesIn_fundiblefo_Data;
import com.test.fundible.Othe_fundiblersInfo;
import com.test.fundible.fundible_00_utils.FundibleConfigs;
import com.test.fundible.fundible_00_utils.Photo_fundibleSelector_fundibleDialog;
import com.test.fundible.fundible_00_http.OkHttpUtil;
import com.test.fundible.fundible_00_utils.image_fundible.Image_fundibleConvert;
import com.test.fundible.fundible_00_utils.FundibleUtil;

import java.io.File;
import java.util.TreeMap;

import pub.devrel.easypermissions.EasyPermissions;

public class OcrVie_fundiblewMana_fundibleger extends BaseProc_fundibleessWid_fundiblegetManager {

    private final FragmentActivity activ_fundibleity;

    private View idcardBgView,drivinglicenseBgView,passportBgView;
    private ImageView idcardImgIv,drivinglicenseImgIv,passportImgIv;
    private TextView idcardTv,drivinglicenseTv,passportTv;
    private ImageView idcardCheckIv, drivinglicenseCheckIv, passportCheckIv;
    private ImageButton photoFrontIb,photoBackIb;
    private TextView photoFrontTv,photoBackTv;
    private View photoBackView;

    private String image1Ur_fundiblel_fundible, image2Ur_fundiblel_fundible;
    private Bitmap image1Bit_fundiblemap_fundible, image2Bitma_fundiblep_fundible;

    private boolean isImageRe_fundibleverse = false;

    private static final String CT_Id_fundibleC ="National ID card", CT_Passp_fundibleort ="Passport", CT_DrvingL_fundibleicense ="Drving license";
    private static final String WD_IdC_fundibleard ="IDCARD", WD_Passpo_fundiblert ="PASSPORT", WD_Drvin_fundiblegLicense ="DRIVING";

    private String select_fundibleType = CT_Id_fundibleC;

    private Runnable startCame_fundibleraRunnable;

    public String imgPa_fundibleth = "";
    public Uri pho_fundibletoUri;

    public static final int Flag_StartCam_fundibleera = 77;

    private ActivityResultLauncher<PickVisualMediaRequest> pickMe_fundibledia;

    private final Runnable processResp_fundibleRunnable, imgUploadRe_fundiblespRunnab_fundiblele;


    public OcrVie_fundiblewMana_fundibleger(View view, Proces_fundiblesIn_fundiblefo_Data data, String page, Runnable processRespRunnable, Runnable imgUploadRespRunnable){
        super(view,data,page);
        activ_fundibleity = (FragmentActivity) mView.getContext();

        this.processResp_fundibleRunnable = processRespRunnable;
        this.imgUploadRe_fundiblespRunnab_fundiblele = imgUploadRespRunnable;

    }

    @Override
    protected void in_fundibleit(){

        View idcardClickView = mView.findViewById(R.id.ifpo_view_idcard_click);
        View drivinglicenseClickView = mView.findViewById(R.id.ifpo_view_drivinglicense_click);
        View passportClickView = mView.findViewById(R.id.ifpo_view_passport_click);
        idcardBgView = mView.findViewById(R.id.ifpo_view_idcard_bg);
        drivinglicenseBgView = mView.findViewById(R.id.ifpo_view_drivinglicense_bg);
        passportBgView = mView.findViewById(R.id.ifpo_view_passport_bg);
        idcardImgIv = mView.findViewById(R.id.ifpo_iv_idcard_img);
        drivinglicenseImgIv = mView.findViewById(R.id.ifpo_iv_drivinglicense_img);
        passportImgIv = mView.findViewById(R.id.ifpo_iv_passport_img);
        idcardTv = mView.findViewById(R.id.ifpo_tv_idcard);
        drivinglicenseTv = mView.findViewById(R.id.ifpo_tv_drivinglicense);
        passportTv = mView.findViewById(R.id.ifpo_tv_passport);
        idcardCheckIv = mView.findViewById(R.id.ifpo_iv_idcard_check);
        drivinglicenseCheckIv = mView.findViewById(R.id.ifpo_iv_drivinglicense_check);
        passportCheckIv = mView.findViewById(R.id.ifpo_iv_passport_check);
        photoFrontIb = mView.findViewById(R.id.ifpo_ib_photo_front);
        photoBackIb = mView.findViewById(R.id.ifpo_ib_photo_back);
        photoFrontTv = mView.findViewById(R.id.ifpo_tv_photo_front);
        photoBackTv = mView.findViewById(R.id.ifpo_tv_photo_back);
        photoBackView = mView.findViewById(R.id.ifpo_view_photo_back);
        
        photoFrontIb.setOnClickListener(v -> {

            OkHttpUtil.getInstance_fundible().uploadEventPoint(TAG,"IMAGE_1_CLICK","");

            new Photo_fundibleSelector_fundibleDialog(
                    mView.getContext(),
                    () -> {//打开相机
                        isImageRe_fundibleverse = false;
                        star_fundibletCame_fundiblera();
                    },
                    () -> {//相册选择
                        isImageRe_fundibleverse = false;
                        ope_fundiblenAl_fundiblebum();
                    },
                    TAG
            ).show();

        });

        photoBackIb.setOnClickListener(v -> {
            OkHttpUtil.getInstance_fundible().uploadEventPoint(TAG,"IMAGE_2_CLICK","");

            new Photo_fundibleSelector_fundibleDialog(
                    mView.getContext(),
                    () -> {//打开相机
                        isImageRe_fundibleverse = true;
                        star_fundibletCame_fundiblera();
                    },
                    () -> {//相册选择
                        isImageRe_fundibleverse = true;
                        ope_fundiblenAl_fundiblebum();
                    },
                    TAG
            ).show();

        });

        idcardClickView.setOnClickListener(v -> checkToIdcard());
        passportClickView.setOnClickListener(v -> checkToPassport());
        drivinglicenseClickView.setOnClickListener(v -> checkToDrivingLicense());

        checkToIdcard();
        
    }

    public void nextC_fundiblelick(String path){
        if (TextUtils.isEmpty(image1Ur_fundiblel_fundible)||(TextUtils.isEmpty(image2Ur_fundiblel_fundible)&&!select_fundibleType.equalsIgnoreCase(CT_Passp_fundibleort))){
            Toast.makeText(mView.getContext(), mView.getContext().getString(R.string.tips_upload_photo),Toast.LENGTH_SHORT).show();
            return;
        }

        startLoading(activ_fundibleity,"");
        OkHttpUtil.getInstance_fundible().uploadUserPrcsInfo(
                path,
                new TreeMap<String,String>(){{
                    put("cardImgUrl", image1Ur_fundiblel_fundible);
                    put("cardBackImgUrl", select_fundibleType.equalsIgnoreCase(CT_Passp_fundibleort) ? "": image2Ur_fundiblel_fundible);
                    put("cardType", getTy_fundiblepeWd());
                }},
                () -> OkHttpUtil.getInstance_fundible().requestUsPrcs(() -> {
                        stopLoading();
                        if (processResp_fundibleRunnable !=null) processResp_fundibleRunnable.run();
                    }
        ));
    }

    @Override
    public boolean checkI_fundiblenput() {
        return false;
    }

    @Override
    public String getInp_fundibleut() {
        return "";
    }


    private void star_fundibletCame_fundiblera() {

        OkHttpUtil.getInstance_fundible().uploadEventPoint(TAG,"START_CAMERA_CLICK","");

        //拍照流程
        startCame_fundibleraRunnable = () -> {
            Intent intent = new Intent();
            intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);

            String imageFilePath = this.getIma_fundiblegeFilePa_fundibleth();
            File imageFile = new File(imageFilePath);
            imgPa_fundibleth = imageFilePath;
            String providerAuthority = Base_fundibleApplication.getInstant().getPackageName() + ".file_provider";
            pho_fundibletoUri = FileProvider.getUriForFile(Base_fundibleApplication.getInstant(), providerAuthority, imageFile);

            intent.putExtra(MediaStore.EXTRA_OUTPUT, pho_fundibletoUri);
            if (activ_fundibleity !=null) activ_fundibleity.startActivityForResult(intent, Flag_StartCam_fundibleera);
        };
        //申请权限
        if (!FundibleUtil.checkPermissions_fundible(mView.getContext(), Manifest.permission.CAMERA)) {
            if (activ_fundibleity !=null)
                EasyPermissions.requestPermissions(activ_fundibleity,
                        activ_fundibleity.getString(R.string.launch_permissions_camera_fundible),
                        FundibleConfigs.PermissionCode_Camera, Manifest.permission.CAMERA);
        } else startCame_fundibleraRunnable.run();
    }

    private void ope_fundiblenAl_fundiblebum() {

        OkHttpUtil.getInstance_fundible().uploadEventPoint(TAG,"OPEN_ALBUM_CLICK","");

        if (pickMe_fundibledia !=null)
            pickMe_fundibledia.launch(
                    new PickVisualMediaRequest.Builder()
                            .setMediaType(ActivityResultContracts.PickVisualMedia.ImageOnly.INSTANCE)
                            .build()
            );
    }

    public void set_fundiblePick_fundibleMe(ActivityResultLauncher<PickVisualMediaRequest> pickMe_fundibledia) {
        this.pickMe_fundibledia = pickMe_fundibledia;
    }

    public void onPh_fundibleot_fundibleoGet() {
        if (pho_fundibletoUri == null) {
            if (isImageRe_fundibleverse) image2Ur_fundiblel_fundible = null;
            else image1Ur_fundiblel_fundible = null;
            Toast.makeText(mView.getContext(), mView.getContext().getString(R.string.tips_upload_photo_again),Toast.LENGTH_SHORT).show();
            return;
        }

        if (!TextUtils.isEmpty(imgPa_fundibleth)) {
            Image_fundibleConvert.start_fundibleConvert_fundibleImage(
                    new File(imgPa_fundibleth),
                    (localPath, thumpImg) -> {
                        if (isImageRe_fundibleverse) image2Bitma_fundiblep_fundible = thumpImg;
                        else image1Bit_fundiblemap_fundible = thumpImg;
                        new Thread(
                                () -> {
                                    startLoading(activ_fundibleity,"");
                                    OkHttpUtil.getInstance_fundible().uploadImage(localPath,() -> {
                                        stopLoading();
                                        if (imgUploadRe_fundiblespRunnab_fundiblele !=null) imgUploadRe_fundiblespRunnab_fundiblele.run();
                                    });
                                }
                        ).start();
                    }
            );
        } else {
            if (isImageRe_fundibleverse) image2Ur_fundiblel_fundible = null;
            else image1Ur_fundiblel_fundible = null;
            Toast.makeText(mView.getContext(), mView.getContext().getString(R.string.tips_upload_photo_again),Toast.LENGTH_SHORT).show();
        }
    }

    public void onPhot_fundibleoUploadRe_fundiblesponse() {

        String imagePath = Othe_fundiblersInfo.getInstance_fundible().getImgPath_fundible();

        if (TextUtils.isEmpty(imagePath)||(!isImageRe_fundibleverse && image1Bit_fundiblemap_fundible ==null)||(isImageRe_fundibleverse && image2Bitma_fundiblep_fundible ==null)){
            Toast.makeText(mView.getContext(), mView.getContext().getString(R.string.tips_upload_photo_again),Toast.LENGTH_SHORT).show();
            return;
        }

        if (isImageRe_fundibleverse){
            this.image2Ur_fundiblel_fundible = imagePath;
            photoBackIb.setImageBitmap(image2Bitma_fundiblep_fundible);
        }else {
            this.image1Ur_fundiblel_fundible = imagePath;
            photoFrontIb.setImageBitmap(image1Bit_fundiblemap_fundible);
        }

    }

    @SuppressLint("SetTextI18n")
    private void checkToIdcard(){

        OkHttpUtil.getInstance_fundible().uploadEventPoint(TAG,"TYPE_ID_CARD_CLICK","");

        idcardBgView.setBackgroundResource(R.drawable.bg_green_ll_rc12dp_border_green_1dp);
        idcardImgIv.setBackgroundResource(R.drawable.img_ocr_idcard_light);
        idcardTv.setTextColor(Base_fundibleApplication.getInstant().getColor(R.color.green_light));
        idcardCheckIv.setVisibility(View.VISIBLE);

        drivinglicenseBgView.setBackgroundResource(R.drawable.bg_gray_rc12dp);
        drivinglicenseImgIv.setBackgroundResource(R.drawable.img_ocr_drivinglicense_gray);
        drivinglicenseTv.setTextColor(Color.parseColor("#FF989597"));
        drivinglicenseCheckIv.setVisibility(View.INVISIBLE);

        passportBgView.setBackgroundResource(R.drawable.bg_gray_rc12dp);
        passportImgIv.setBackgroundResource(R.drawable.img_ocr_passport_gray);
        passportTv.setTextColor(Color.parseColor("#FF989597"));
        passportCheckIv.setVisibility(View.INVISIBLE);

        clearI_fundiblemg();

        select_fundibleType = CT_Id_fundibleC;
        photoFrontTv.setText(mView.getContext().getString(R.string.ocr_desc_idcard_front));
        photoBackTv.setText(mView.getContext().getString(R.string.ocr_desc_idcard_back));
        photoBackView.setVisibility(View.VISIBLE);
    }

    @SuppressLint("SetTextI18n")
    private void checkToPassport(){

        OkHttpUtil.getInstance_fundible().uploadEventPoint(TAG,"TYPE_PASSPORT_CLICK","");

        idcardBgView.setBackgroundResource(R.drawable.bg_gray_rc12dp);
        idcardImgIv.setBackgroundResource(R.drawable.img_ocr_idcard_gray);
        idcardTv.setTextColor(Color.parseColor("#FF989597"));
        idcardCheckIv.setVisibility(View.INVISIBLE);

        drivinglicenseBgView.setBackgroundResource(R.drawable.bg_gray_rc12dp);
        drivinglicenseImgIv.setBackgroundResource(R.drawable.img_ocr_drivinglicense_gray);
        drivinglicenseTv.setTextColor(Color.parseColor("#FF989597"));
        drivinglicenseCheckIv.setVisibility(View.INVISIBLE);

        passportBgView.setBackgroundResource(R.drawable.bg_green_ll_rc12dp_border_green_1dp);
        passportImgIv.setBackgroundResource(R.drawable.img_ocr_passport_light);
        passportTv.setTextColor(Base_fundibleApplication.getInstant().getColor(R.color.green_light));
        passportCheckIv.setVisibility(View.VISIBLE);

        clearI_fundiblemg();

        select_fundibleType = CT_Passp_fundibleort;
        photoFrontTv.setText(mView.getContext().getString(R.string.ocr_desc_passport));
        photoBackView.setVisibility(View.GONE);

    }

    @SuppressLint("SetTextI18n")
    private void checkToDrivingLicense(){

        OkHttpUtil.getInstance_fundible().uploadEventPoint(TAG,"TYPE_DRIVING_LICENSE_CLICK","");

        idcardBgView.setBackgroundResource(R.drawable.bg_gray_rc12dp);
        idcardImgIv.setBackgroundResource(R.drawable.img_ocr_idcard_gray);
        idcardTv.setTextColor(Color.parseColor("#FF989597"));
        idcardCheckIv.setVisibility(View.INVISIBLE);

        drivinglicenseBgView.setBackgroundResource(R.drawable.bg_green_ll_rc12dp_border_green_1dp);
        drivinglicenseImgIv.setBackgroundResource(R.drawable.img_ocr_drivinglicense_light);
        drivinglicenseTv.setTextColor(Base_fundibleApplication.getInstant().getColor(R.color.green_light));
        drivinglicenseCheckIv.setVisibility(View.VISIBLE);

        passportBgView.setBackgroundResource(R.drawable.bg_gray_rc12dp);
        passportImgIv.setBackgroundResource(R.drawable.img_ocr_passport_gray);
        passportTv.setTextColor(Color.parseColor("#FF989597"));
        passportCheckIv.setVisibility(View.INVISIBLE);

        clearI_fundiblemg();

        select_fundibleType = CT_DrvingL_fundibleicense;
        photoFrontTv.setText(mView.getContext().getString(R.string.ocr_desc_license_front));
        photoBackTv.setText(mView.getContext().getString(R.string.ocr_desc_license_back));
        photoBackView.setVisibility(View.VISIBLE);

    }

    private void clearI_fundiblemg(){
        image1Ur_fundiblel_fundible = "";
        image2Ur_fundiblel_fundible = "";
        image1Bit_fundiblemap_fundible = null;
        image2Bitma_fundiblep_fundible = null;

        photoFrontIb.setImageResource(R.drawable.img_ocr_photo_front);
        photoBackIb.setImageResource(R.drawable.img_ocr_photo_back);
    }

    private String getTy_fundiblepeWd(){
        switch (select_fundibleType){
            case CT_Id_fundibleC:
                return WD_IdC_fundibleard;
            case CT_Passp_fundibleort:
                return WD_Passpo_fundiblert;
            case CT_DrvingL_fundibleicense:
                return WD_Drvin_fundiblegLicense;
        }
        return "";
    }

    public void onCam_fundibleeraPermissio_fundiblenAgree(){
        if (startCame_fundibleraRunnable !=null) startCame_fundibleraRunnable.run();
    }

    /**
     * 获取图片路径
     */
    private String getIma_fundiblegeFilePa_fundibleth() {
        String pictureId = System.currentTimeMillis() + "";
        String imgDir = getSa_fundiblendboxFolde_fundiblerPath();
        return (imgDir + File.separator + pictureId + ".jpg");
    }

    /**
     * 获取沙盒路径
     */
    private String getSa_fundiblendboxFolde_fundiblerPath() {
        String inAppFolder = Base_fundibleApplication.getInstant().getFilesDir().getAbsolutePath();
        inAppFolder += File.separator;
        inAppFolder += FundibleConfigs.fundibleProduct;
        inAppFolder += "_PICS";

        File folderFile = new File(inAppFolder);
        if (!folderFile.exists()) {
            folderFile.mkdirs();
        }

        return inAppFolder;
    }

}
